using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace CSharpPro._1028;

public class UserService : IUserService
{
    // 使用泛型集合保存用户信息
    private readonly List<User> _users = new List<User>();

    public void Run(string[] args)
    {
        ShowMainMenu();
    }
    
    /// 显示主菜单并处理用户选择
    public void ShowMainMenu()
    {
        while (true)
        {
            Console.Clear();
            Console.WriteLine("===== 用户系统 =====");
            Console.WriteLine("1. 登录");
            Console.WriteLine("2. 注册");
            Console.WriteLine("3. 退出");
            Console.WriteLine("====================");
            Console.Write("请选择功能 (1-3): ");

            string input = Console.ReadLine();
            if (!int.TryParse(input, out int choice))
            {
                Console.WriteLine("请输入有效数字！按任意键继续...");
                Console.ReadKey();
                continue;
            }

            switch (choice)
            {
                case 1:
                    bool loginSuccess = Login(out string username);
                    if (loginSuccess)
                    {
                        Console.WriteLine($"✅ 登录成功！欢迎回来，{username}！");
                        Console.WriteLine("进入系统首页...（按任意键返回主菜单）");
                        Console.ReadKey();
                    }
                    break;
                case 2:
                    bool registerSuccess = Register();
                    if (registerSuccess)
                    {
                        Console.WriteLine("注册成功！按任意键返回主菜单...");
                        Console.ReadKey();
                    }
                    break;
                case 3:
                    Console.WriteLine("谢谢使用，再见！");
                    return;
                default:
                    Console.WriteLine("请输入1-3之间的数字！按任意键继续...");
                    Console.ReadKey();
                    break;
            }
        }
    }
    
    /// 用户注册功能
    /// 注册是否成功
    public bool Register()
    {
        Console.Clear();
        Console.WriteLine("===== 用户注册 =====");

        // 获取并验证用户名
        string username;
        while (true)
        {
            Console.Write("请输入用户名: ");
            username = Console.ReadLine()?.Trim();
            
            var (isValid, message) = ValidateUsername(username);
            if (!isValid)
            {
                Console.WriteLine($"{message}");
                continue;
            }

            // 使用foreach循环检查用户名是否已存在
            bool userExists = false;
            foreach (var user in _users)
            {
                if (user.Username == username)
                {
                    userExists = true;
                    break;
                }
            }

            if (userExists)
            {
                Console.WriteLine("用户名已存在，请选择其他用户名");
                continue;
            }

            break;
        }

        // 获取并验证密码
        string password;
        while (true)
        {
            Console.Write("请输入密码: ");
            password = ReadPassword();
            
            var (isValid, message) = ValidatePassword(password);
            if (!isValid)
            {
                Console.WriteLine($"{message}");
                continue;
            }

            // 验证确认密码
            Console.Write("请确认密码: ");
            string confirmPassword = ReadPassword();
            
            if (password != confirmPassword)
            {
                Console.WriteLine("密码与确认密码不一致");
                continue;
            }

            break;
        }

        // 注册用户
        _users.Add(new User(username, password));
        return true;
    }
    
    /// 用户登录功能
    /// <param name="username">登录成功的用户名</param>
    /// <returns>登录是否成功</returns>
    public bool Login(out string username)
    {
        username = string.Empty;
        Console.Clear();
        Console.WriteLine("===== 用户登录 =====");

        Console.Write("请输入用户名: ");
        string inputUsername = Console.ReadLine()?.Trim();

        Console.Write("请输入密码: ");
        string inputPassword = ReadPassword();

        // 验证登录信息
        if (string.IsNullOrWhiteSpace(inputUsername) || string.IsNullOrWhiteSpace(inputPassword))
        {
            Console.WriteLine("用户名或密码不可为空！");
            Console.WriteLine("按任意键重新尝试...");
            Console.ReadKey();
            return false;
        }

        // 使用foreach循环验证用户信息
        foreach (var user in _users)
        {
            if (user.Username == inputUsername)
            {
                if (user.Password == inputPassword)
                {
                    username = inputUsername;
                    return true;
                }
                Console.WriteLine("密码错误！");
                Console.WriteLine("按任意键重新尝试...");
                Console.ReadKey();
                return false;
            }
        }

        Console.WriteLine("用户名不存在！");
        Console.WriteLine("按任意键重新尝试...");
        Console.ReadKey();
        return false;
    }

    /// <summary>
    /// 验证用户名是否符合规则
    /// </summary>
    protected (bool isValid, string message) ValidateUsername(string username)
    {
        if (string.IsNullOrWhiteSpace(username))
        {
            return (false, "用户名不可为空");
        }

        if (username.Length < 3 || username.Length > 15)
        {
            return (false, "用户名长度必须为3-15个字符");
        }

        // 验证只能包含字母、数字和下划线
        if (!Regex.IsMatch(username, @"^[a-zA-Z0-9_]+$"))
        {
            return (false, "用户名只能包含字母、数字和下划线");
        }

        return (true, "用户名有效");
    }

    /// <summary>
    /// 验证密码是否符合规则
    /// </summary>
    protected (bool isValid, string message) ValidatePassword(string password)
    {
        if (string.IsNullOrWhiteSpace(password))
        {
            return (false, "密码不可为空");
        }

        if (password.Length < 6 || password.Length > 20)
        {
            return (false, "密码长度必须为6-20个字符");
        }

        // 验证包含至少1个大写字母、1个小写字母和1个数字
        if (!Regex.IsMatch(password, @"[A-Z]") || 
            !Regex.IsMatch(password, @"[a-z]") || 
            !Regex.IsMatch(password, @"[0-9]"))
        {
            return (false, "密码必须包含至少1个大写字母、1个小写字母和1个数字");
        }

        return (true, "密码有效");
    }

    /// <summary>
    /// 读取密码，不显示输入的字符
    /// </summary>
    protected string ReadPassword()
    {
        string password = "";
        ConsoleKeyInfo key;

        do
        {
            key = Console.ReadKey(true);
            
            // 处理退格键
            if (key.Key == ConsoleKey.Backspace && password.Length > 0)
            {
                password = password.Remove(password.Length - 1);
                Console.Write("\b \b"); 
            }
            // 处理回车键
            else if (key.Key != ConsoleKey.Enter)
            {
                password += key.KeyChar;
                Console.Write("*"); 
            }
        } while (key.Key != ConsoleKey.Enter);

        Console.WriteLine(); 
        return password;
    }
}